package cn.candy.user.service.impl;

import cn.candy.basic.exception.BusinessExcpetion;
import cn.candy.basic.service.impl.BaseServiceImpl;
import cn.candy.basic.util.MD5Utils;
import cn.candy.basic.util.StrUtils;
import cn.candy.user.constant.UserConstant;
import cn.candy.user.domain.Logininfo;
import cn.candy.user.domain.User;
import cn.candy.user.dto.UserDto;
import cn.candy.user.mapper.LogininfoMapper;
import cn.candy.user.mapper.UserMapper;
import cn.candy.user.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;


/**
 * 用户业务实现类
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    @Override
    public void sendSms(String phone) {
        //1.验证 = 空值验证 + 是否注册过的验证
        if (!StringUtils.hasLength(phone)) {
            throw new BusinessExcpetion("请输入正确的手机号!!!");
        }
        User user = userMapper.findByPhone(phone);
        if(user != null){
            throw new BusinessExcpetion("该号码已经注册，请直接登录!!!");
        }

        //获取redis中保存的验证码
        Object obj = redisTemplate.opsForValue().get(UserConstant.REGISTER_CODE_PREFIX + phone);
        String code = null;
        if(obj != null){ //验证码没有过期
            //获取redis中以前保存的验证码
            code = obj.toString().split(":")[0];
            //获取以前保存的时间
            String timeString = obj.toString().split(":")[1];
            if(System.currentTimeMillis() - Long.parseLong(timeString) < 1*60*1000){ //没有过重发时间
                throw new BusinessExcpetion("不能重复发送验证码");
            }
        }else{ //过期了 或 第一次发送
            //重新生成验证码
            code = StrUtils.getRandomString(4);
        }

        redisTemplate.opsForValue().set(UserConstant.REGISTER_CODE_PREFIX + phone
                ,code+":"+System.currentTimeMillis(),3, TimeUnit.MINUTES);
        //SmsUtil.sendMsg(phone,"你的验证码是：" + code + ",请在3分钟之内使用");
        System.out.println("你的验证码是：" + code + ",请在3分钟之内使用");
    }

    @Override
    @Transactional
    public void phoneRegister(UserDto userDto) {
        String phone = userDto.getPhone();
        String verifycode = userDto.getVerifycode();
        String password = userDto.getPassword();
        String rePassword = userDto.getRePassword();

        //1.校验
        //1.1.空值校验
        if(StringUtils.isEmpty(phone)
                || StringUtils.isEmpty(verifycode)
                || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(rePassword)){
            throw new BusinessExcpetion("请输入正确的数据!!!");
        }
        //1.2.两次密码是否相同
        if(!password.equals(rePassword)){
            throw new BusinessExcpetion("两次密码不一致!!!");
        }
        //1.3.验证码是否过期
        Object obj = redisTemplate.opsForValue().get(UserConstant.REGISTER_CODE_PREFIX + phone);
        if(obj == null){
            throw new BusinessExcpetion("验证码无效，请重新获取!!!");
        }
        //1.4.验证码是否正确  //  9527:1223555555
        String codeTmp = obj.toString().split(":")[0];
        if(!codeTmp.equalsIgnoreCase(verifycode)){
            throw new BusinessExcpetion("验证码错误!!!");
        }
        //1.5.手机号码是否已经被注册了【如果验证码验证之后，这一步可以不要】
        User userTmp = userMapper.findByPhone(phone);
        if(userTmp != null){//在用户表中已经有该手机号
            throw new BusinessExcpetion("该号码已经注册，请直接登录!!!");
        }

        //2.保存数据
        //2.1.先保存t_logininfo
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);

        logininfoMapper.save(logininfo);//自增
        //2.2.再保存t_user
        user.setLogininfo_id(logininfo.getId());
        //user.setLogininfo(logininfo);
        userMapper.save(user);
    }

    @Override
    public void sendBinderCode(String phone) {
        //1.验证 = 空值验证 + 是否注册过的验证
        if (StringUtils.isEmpty(phone)) {
            throw new BusinessExcpetion("请输入正确的手机号!!!");
        }
//        User user = userMapper.findByPhone(phone);
//        if(user != null){
//            throw new BusinessExcpetion("该号码已经注册，请直接登录!!!");
//        }

        //获取redis中保存的验证码
        Object obj = redisTemplate.opsForValue().get(UserConstant.BINDER_CODE_PREFIX + phone);
        String code = null;
        if(obj != null){ //验证码没有过期
            //获取redis中以前保存的验证码
            code = obj.toString().split(":")[0];
            //获取以前保存的时间
            String timeString = obj.toString().split(":")[1];
            if(System.currentTimeMillis() - Long.parseLong(timeString) < 1*60*1000){ //没有过重发时间
                throw new BusinessExcpetion("不能重复发送验证码");
            }
        }else{ //过期了 或 第一次发送
            //重新生成验证码
            code = StrUtils.getRandomString(4);
        }

        redisTemplate.opsForValue().set(UserConstant.BINDER_CODE_PREFIX + phone
                ,code+":"+System.currentTimeMillis(),3, TimeUnit.MINUTES);
        //SmsUtil.sendMsg(phone,"你的验证码是：" + code + ",请在3分钟之内使用");
        System.out.println("你的验证码是：" + code + ",请在3分钟之内使用");

    }

    private User userDto2User(UserDto userDto) {
        User user = new User();
        user.setUsername(userDto.getPhone());
        user.setPhone(userDto.getPhone());
        //获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //获取加密之后的密码
        String md5Pwd = MD5Utils.encrypByMd5(userDto.getPassword()+salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //按照同名属性赋值【username，email，phone，salt，password】
        BeanUtils.copyProperties(user,logininfo);
        //当前对象是用户
        logininfo.setType(1);
        return logininfo;
    }

    @Override //@TODO
    public void add(User user) {
        super.add(user);
    }

    @Override //@TODO
    public void del(Long id) {
        super.del(id);
    }

    @Override //@TODO
    public void update(User user) {
        super.update(user);
    }
}
